<?php

namespace App\Models;

use App\Models\traits\Search;
use App\Models\traits\SerializeDate;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Record extends Model
{
    use HasFactory, SerializeDate, Search, SoftDeletes;

    public $fillable = ['user_id', 'wechat_id', 'video_id', 'order_img', 'expired_at', 'remark', 'video_nickname', 'start_at'];
    public $appends = ['username', 'canupdate', 'departmentname', 'canedit'];

    public function getUsernameAttribute()
    {
        return $this->user()?$this->user()->value("name"):"";
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * @return bool
     * 条件1：30日内不允许修改，条件2：31日至35日修改，并从新计算开始时间；条件3：如果到达35日任然未修改，这该数据被系统删除清理
     */
    public function getCanupdateAttribute()
    {
        $now = time();
        $start_at = strtotime($this->start_at);
        $diff = ($now - $start_at) / 86400;
        if ($diff < 30) {
            return false;
        } elseif ($diff >= 30 && $diff < 35) {
            return true;
        } else {
            return false;
        }
    }

//部门名称
    public function getDepartmentnameAttribute()
    {
        return $this->user?$this->user->department()->value("name"):"";
    }

//    是否可修改
    public function getCaneditAttribute()
    {
        if (auth()->id() == 1) {
            return true;
        }
//是自己提交的，可修改
        if ($this->user_id == auth()->id()) {
            return true;
        } else {
            return false;
        }
    }
}
